package com.tbit.main.controller;

import com.tbit.main.common.JsonResult;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.main.constant.OperateLog;
import com.tbit.main.constant.RedisConstant;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.JPushUserConfig;
import com.tbit.main.service.JPushUserConfigService;
import com.tbit.main.service.RedisService;
import com.tbit.main.service.TokenService;
import com.tbit.main.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 极光推送
 *
 * @author LMY
 * @create 2021-08-30 17:11
 */
@RestController
@RequestMapping("/jpush")
public class JPushController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private JPushUserConfigService jPushUserConfigService;
    @Autowired
    private RedisService redisService;

    /**
     * 极光推送regId更新
     *
     * @param token
     * @param regId
     * @return
     */
    @RequestMapping("/add")
    @OperateLog(module = ModuleEnum.JPUSH, methods = MethodEnum.JPUSH_ADD)
    public JsonResult add(String token, String regId) {

        AccountUser accountUser = tokenService.getAccount(token);

        JPushUserConfig jPushUserConfig = jPushUserConfigService.find(accountUser.getAccountUserId());

        if (jPushUserConfig == null) {
            LogUtil.info(accountUser.getAccountUserId() + "登陆regId：" + regId);
            jPushUserConfigService.add(accountUser.getAccountUserId(), regId);
        } else {
            if (!jPushUserConfig.getRegId().equals(regId)) {
                LogUtil.info(accountUser.getAccountUserId() + "修改regId：" + regId);
                jPushUserConfigService.update(accountUser.getAccountUserId(), regId);
            }
        }

        String key = accountUser.getAccountUserId() + "_" + RedisConstant.REDIS_WORK_PUSH;
        redisService.add(key, regId, 60 * 60 * 24 * 7);

        return JsonResult.succ();
    }

    /**
     * 超时删除
     *
     * @param token
     * @param regId
     * @return
     */
    @RequestMapping("/state")
    public JsonResult state(String token, String regId) {
        AccountUser accountUser = tokenService.getAccount(token);

        String key = accountUser.getAccountUserId() + "_" + RedisConstant.REDIS_WORK_PUSH;
        LogUtil.info(accountUser.getAccountUserId() + "超时删除：" + regId);
        redisService.del(key);
        return JsonResult.succ();
    }
}
